<?php
/**
 * @file
 * Strategy pattern to adapter for database.
 *
 * @category   rpd
 * @package    Db
 * @subpackage Db
 * @copyright  Copyright (c) 2010 Rpd-Team (http://code.google.com/p/rpd)
 * @license    BSD License
 * @link       http://code.google.com/p/rpd/wiki/Db
 * @since      0.0.1
 * @version    0.0.1
 */

 /**
 * Loads the specified adapter and creates a connection to the database.
 *
 * Db can establish a connection to every type of database for which the needed
 * PHP extension is given.
 *
 * @code
 *   echo "Quelltext";
 * @endcode
 *
 * See also:
 *  @see
 *
 * @author pretzlaw
 */

class Db implements Db_Interface
{
	private static $_obj = array();

	private $_data = array(
		'host' =>       'localhost',
		'user' =>       '',
		'password' =>   '',
		'database' =>   '',
		'driver' =>     'mysql',
		'persistent' => false,
		'prefix' =>     '',
		'encoding' =>   ''
	);

	public static function get($name = "STD")
	{
		if (isset(self::$_obj[$name]))
		{
			return self::$_obj[$name];
		}

		$cfg = new Config("db", $name);
		self::$_obj[$name] = new Db($cfg);

		self::$_obj[$name]->database($cfg["database"]);

		if ($cfg["encoding"])
		{
			self::$_obj[$name]->encoding($cfg["encoding"]);
		}

		return self::$_obj[$name];
	}

	public function encoding($s)
	{
		$this->_sql->encoding($s);
	}

	public function database($s)
	{
		$this->_sql->database($s);
	}

	public function query($s)
	{
		return $this->_sql->query($s);
	}

	public function quote($s)
	{
		return $this->_sql->quote($s);
	}

public function __construct(
		$host =       'localhost',
		$user =       '',
		$password =   '',
		$database =   'database',
		$driver =     'mysql',
		$persistent = false,
		$prefix =     '',
		$encoding =   'utf8'
	)
	{
		if (is_array($host) || $host instanceof ArrayAccess)
		{
			// migrate array into simple variables
			$user =       $host["user"];
			$password =   $host["password"];
			$database =   $host["database"];
			$driver =     $host["driver"];
			$persistent = $host["persistent"];
			$prefix =     $host["prefix"];
			$encoding =   $host["encoding"];

			$host =       $host["host"];
		}

		switch (strtolower($driver))
		{
			case "mysql":
				$this->_sql = new Db_Adapter_MySQL(
					$host,
					$user,
					$password,
					$database,
					$driver,
					$persistent,
					$prefix,
					$encoding
				);
				break;
		}

		if ($database !== NULL)
		{
			$this->database($database);
		}

		if ($encoding !== NULL)
		{
			$this->encoding($encoding);
		}
	}
}